package com.hoperun.preparedisplay.activity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.hoperun.preparedisplay.R;
import com.hoperun.preparedisplay.util.Setting;
import com.hoperun.preparedisplay.util.WebServiceUtils;

public class MainActivity extends Activity {
	
	private volatile JSONArray dataBuffer = new JSONArray();
	private JSONArray data = new JSONArray();
	
	private int index = 0;
	
	private MyAdapter myAdapter;
	private TextView footer;
	
	private int numColumns; // 列数
	private int numRows;     // 行数
	private int numItemsPerPage; 
	
	{
		Setting.parseXml();
		numColumns = Setting.getColumnNum();
		numRows = Setting.getRowNum();
		numItemsPerPage = numColumns * numRows;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		footer = (TextView) findViewById(R.id.footer);
		
		
		thread.start();
//		getData() ;
		thread2.start();
		GridView gridView = (GridView) findViewById(R.id.grid_view);
		myAdapter = new MyAdapter();
		gridView.setAdapter(myAdapter);
		gridView.setNumColumns(numColumns);
	}
	
	/**
	 * 该线程负责访问服务器，获取数据
	 */
	private Thread thread = new Thread() {
		public void run() {
			
				try {
					while(true) {
						String result = WebServiceUtils.getMachineInfoList(Setting.getProMachine());
						if(result != null ) {
							if( result.equals("[]")) {
								dataBuffer = new JSONArray();
								JSONObject json = new JSONObject();
								json.put(WebServiceUtils.MACHINE_NO, 0);
								json.put(WebServiceUtils.MACHINE_STATE, 0);
								json.put(WebServiceUtils.MACHINE_PLANTYPE, 0);
								dataBuffer.put(json);
							} else {
								dataBuffer = new JSONArray(result);
							}
							
						}
						sleep(Setting.getRequestRate());
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
		}
	};
	
	/**
	 * 该线程负责数据分页显示
	 */
	private Thread thread2 = new Thread() {
		public void run() {
				
			try {
				while(true) {
					if(dataBuffer.length() > 0) {
						JSONObject json = dataBuffer.getJSONObject(0);
						if(!json.has(WebServiceUtils.OPT_FLAG))
							mHandler.sendEmptyMessage(0);
						else if(json.getInt(WebServiceUtils.OPT_FLAG) == 1) {
							Message msg = Message.obtain();
							Bundle bundle = new Bundle();
							bundle.putString(WebServiceUtils.MSG_INFO, json.getString(WebServiceUtils.MSG_INFO));
							msg.setData(bundle);
							msg.what = 1;
							mHandler.sendMessage(msg);
						}
						sleep(Setting.getPageRate());
					} else {
						sleep(100);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
				
		}
	};
	private Handler mHandler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 0) {
				if(dataBuffer.length() - (index + 1) * numItemsPerPage > 0 ) {
					data = subJsonArray(index * numItemsPerPage, (index + 1) * numItemsPerPage);
				} else {
					data = subJsonArray(index * numItemsPerPage, dataBuffer.length());
				}
				
				myAdapter.notifyDataSetChanged();
				int pageNum = dataBuffer.length() % numItemsPerPage == 0?dataBuffer.length() / numItemsPerPage
						: dataBuffer.length() / numItemsPerPage + 1;
				index++;
				footer.setText(index + "/" + pageNum);
				
				if(index * numItemsPerPage > dataBuffer.length()) {
					index = 0;
				}
			} else if (msg.what == 1) {
				String info = msg.getData().getString(WebServiceUtils.MSG_INFO);
				if(info.contains("SocketTimeoutException")) {
					Toast.makeText(getApplicationContext(), "网络连接超时，请检查网络\nVượt quá thời gian liên kết, kiểm tra lại mạng", Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(getApplicationContext(), info, Toast.LENGTH_LONG).show();
				}
			}
		}
	};
	
	private JSONArray subJsonArray(int start,int end) {
		JSONArray jsonArray = new JSONArray();
		for (int i = start; i < end; i++) {
			
			try {
				jsonArray.put(dataBuffer.getJSONObject(i));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return jsonArray;
	}
	// 测试数据
//	int count = 1;
//	void getData() {
//		new Thread() {
//			@Override
//			public void run() {
//				while(dataBuffer.length() < 203){
//						JSONObject json = new JSONObject();
//						try {
//							if(count % 2 == 0) {
//								json.put("STATE", 1);
//							}else {
//								json.put("STATE", 2);
//							}
//							json.put("MACHINENO", 3000 + count);
//							synchronized (this) {
//								dataBuffer.put(json);
//							}
//							count++;
//							sleep(100);
//						} catch (JSONException e) {
//							e.printStackTrace();
//						}  catch (InterruptedException e) {
//							e.printStackTrace();
//						}
//				}
//			}
//		}.start();
//		
//	}
	
	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return data.length();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			try {
				
				JSONObject json = data.getJSONObject(position);
			
				ViewHolder viewHolder;
				if(convertView == null) {
					viewHolder = new ViewHolder();
					convertView =  getLayoutInflater().inflate(R.layout.list_item, null);
					viewHolder.textview = (TextView) convertView.findViewById(R.id.textview);
					convertView.setTag(viewHolder);
				}
				
				viewHolder = (ViewHolder) convertView.getTag();
				if(json.getInt(WebServiceUtils.MACHINE_STATE) == 0) {
					convertView.setVisibility(View.GONE);
				}
				// 设置已呼叫或已打印显示的颜色
				if (json.getInt(WebServiceUtils.MACHINE_STATE) == 1
						&& json.getInt(WebServiceUtils.MACHINE_PLANTYPE) == 1) {
					// 不是试样的已呼叫显示红色
					viewHolder.textview.setText(json.getString(WebServiceUtils.MACHINE_NO));
					viewHolder.textview.setTextColor(getResources().getColor(R.color.textcolor));
					viewHolder.textview.setBackgroundColor(getResources().getColor(R.color.red));
					convertView.setVisibility(View.VISIBLE);
				} else if (json.getInt(WebServiceUtils.MACHINE_STATE) == 2) {
					// 已打印显示绿色
					viewHolder.textview.setText(json.getString(WebServiceUtils.MACHINE_NO));
					viewHolder.textview.setBackgroundColor(getResources().getColor(R.color.green));
					viewHolder.textview.setTextColor(getResources().getColor(R.color.textcolor));
					convertView.setVisibility(View.VISIBLE);
				} else if (json.getInt(WebServiceUtils.MACHINE_STATE) == 1
						&& json.getInt(WebServiceUtils.MACHINE_PLANTYPE) == 0) {
					// 试样的已呼叫显示黄色
					viewHolder.textview.setText(json.getString(WebServiceUtils.MACHINE_NO));
					viewHolder.textview.setTextColor(getResources().getColor(R.color.textcolor));
					viewHolder.textview.setBackgroundColor(getResources().getColor(R.color.yellow));
					convertView.setVisibility(View.VISIBLE);
				}
				 else if (json.getInt(WebServiceUtils.MACHINE_STATE) == 4) {
						// 剥纱完成  显示 橘黄色
						viewHolder.textview.setText(json.getString(WebServiceUtils.MACHINE_NO));
						viewHolder.textview.setTextColor(getResources().getColor(R.color.textcolor));
						viewHolder.textview.setBackgroundColor(getResources().getColor(R.color.orange));
						convertView.setVisibility(View.VISIBLE);
					}
				 else if (json.getInt(WebServiceUtils.MACHINE_STATE) == 5) {
						// 已送达 显示蓝色
						viewHolder.textview.setText(json.getString(WebServiceUtils.MACHINE_NO));
						viewHolder.textview.setTextColor(getResources().getColor(R.color.textcolor));
						viewHolder.textview.setBackgroundColor(getResources().getColor(R.color.blue));
						convertView.setVisibility(View.VISIBLE);
					}
				 else if (json.getInt(WebServiceUtils.MACHINE_STATE) == 6) {
						// 退纱  显示 粉色
						viewHolder.textview.setText(json.getString(WebServiceUtils.MACHINE_NO));
						viewHolder.textview.setTextColor(getResources().getColor(R.color.textcolor));
						viewHolder.textview.setBackgroundColor(getResources().getColor(R.color.pink));
						convertView.setVisibility(View.VISIBLE);
					}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return convertView;
		}
		
		class ViewHolder {
			TextView textview;
		}
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		thread.interrupt();
		thread2.interrupt();
		thread = null;
		thread2 = null;
	}

}
